use crate::ui::{LWindowInfo, PageUI};
use crate::weidget::create_ui::{
    create_button_ui, create_combo_box_ui, create_edit_ui, create_edit_ui_wh,
};
use eframe::emath::Rect;
use eframe::epaint::{Color32, FontId, Margin};
use egui::{Align, Area, Button, ComboBox, Label, Layout, RichText, TextEdit, Ui, pos2, vec2};


pub(crate) struct UIChatMsg {
    content: String,
    client_id: String,
    sender_id: String,
    msg_list: Vec<String>,
}

impl UIChatMsg {
    pub(crate) fn new() -> Self {
        Self {
            content: "".to_string(),
            client_id: "".to_string(),
            sender_id: "".to_string(),
            msg_list: Vec::new(),
        }
    }

    /* 建立mqtt 连接 */
    fn create_mqtt(&self){
        let client_id = self.client_id.clone();
        tokio::spawn(async {
            lipo_mqtt_client::lmqtt::create_mqtt(client_id, "12345".to_string(), "12345678".to_string()).await.unwrap()
        });
    }

    fn send_msg(&self){
        let client_id = self.client_id.clone();
        let sender_id = &self.sender_id;
        let content = self.content.clone();
        lipo_mqtt_client::send_text(client_id, sender_id, content)
    }

    fn send_disconnent(&self){
        tokio::spawn(async move {
            lipo_mqtt_client::lmqtt::disconnect().await;
        });
    }

}

impl PageUI for UIChatMsg {
    fn show_ui(&mut self, ui: &mut Ui, win_info: LWindowInfo) {
        let win_width = ui.available_width();

        let edit_width = 400.0;

        ui.heading("聊天室");

        ui.add_space(40.0);

        ui.horizontal_top(|ui| {
            ui.set_height(40.0);
            ui.label("自己的ID");
            create_edit_ui_wh(ui, 160.0, 40.0, &mut self.client_id);

            ui.add_space(20.0);

            ui.label("发送端的ID");
            create_edit_ui_wh(ui, 160.0, 40.0, &mut self.sender_id);
            create_button_ui(ui,"建立连接", || {
                self.create_mqtt()
            });
        });

        create_edit_ui(ui, edit_width, &mut self.content);
        
        ui.horizontal(|ui| {
            create_button_ui(ui, "发送消息", || {
                self.send_msg();
            });

            ui.add_space(20.0);

            create_button_ui(ui, "断开连接", || {
                self.send_disconnent();
            });

        });
        

        egui::scroll_area::ScrollArea::vertical().show(ui, |ui| {
            egui::Grid::new("lll").num_columns(1).show(ui, |ui| {
                
            });
        });
    }
}


